package com.pignest.hotel.service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.hibernate.type.Type;

import com.pignest.hotel.dao.hibernate.CommonHibernateDao;

/** 
 * service 基类, 实现基本(CRUD)操作
 *  */
public abstract class BaseService {

	protected CommonHibernateDao dao;
	
	public void insert(Object o) {
		dao.insert(o);
	}
	
	public void update(Object o) {
		dao.update(o);
	}
	public void insertOrUpdate(Object o)
	{
		dao.insertOrUpdate(o);
	}
	
	public void saveAll(Collection<?> entities) {
		dao.saveAll(entities);
	}
	
	public void delete(Object o) {
		dao.delete(o);
	}
	
	public <T> void delete(Class<T> clz, Serializable id) {
		dao.delete(clz, id);
	}
	
	public <T> T get(Class<T> clz, Serializable id) {
		return dao.get(clz, id);
	}
	
	public <T> T get(Class<T> clazz, String key, Object value) {
		return dao.get(clazz, key, value);
	}
	
	public <T> List<T> listAll(Class<T> clz) {
		return dao.listAll(clz);
	}
	
	public void setCommonDao(CommonHibernateDao dao) {
		this.dao = dao;
	}
	public <T> List<T>find(String sHql){
		return this.dao.find(sHql);
	}
	public <T>List<T> queryPageHql(String hql,int start,int length){
		return this.dao.getListForPage(hql, start, length);
	}
	
	public <T> int count(Class<T> clazz, String search, Object[] values, Type[] types) {
		return dao.count(clazz, search, values, types);
	}
	
	public <T> List<T> query(Class<T> clazz, String search, 
			int pageSize, int pageIndex, Object[] values, Type[] types) {
		return dao.query(clazz, search, pageSize, pageIndex, values, types);
	}

	public <T> List<T> query(Class<T> clazz, String search, Object[] values, Type[] types) {
		return dao.query(clazz, search, 0, 0, values, types);
	}
	
    public void executeInTransaction(Runnable r) {
    	if (r != null)
    		r.run();
    }

	protected <T> T uniqueResult(List<T> list) {
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

}
